<template>
    <view class="bg-[#F6F7F9] min-h-screen relative">
        <up-navbar title="添加新地址" :safeAreaInsetTop="true" bgColor="#FFF" :placeholder="true">
            <template #left>
                <view class="flex px-[24rpx] py-[16rpx] border-[1rpx] border-slate-200 rounded-[38rpx]">
                    <up-icon name="arrow-left" size="19" @click="goback"></up-icon>
                    <up-line direction="column" :hairline="false" length="16" margin="0 8px"></up-line>
                    <up-icon name="home" size="20" @click="gohome"></up-icon>
                </view>
            </template>
        </up-navbar>
        <view class="px-[30rpx] bg-[#fff] mb-[20rpx]">
            <up-form labelPosition="left" :errorType="errorType" :model="form" :rules="rules" ref="uFormRef" labelWidth="140rpx">
                <up-form-item label="收货人" prop="receiveName" borderBottom>
                    <up-input v-model="form.receiveName" border="none" placeholder="姓名"></up-input>
                </up-form-item>
                <up-form-item label="联系电话" prop="mobile" borderBottom>
                    <up-input v-model="form.mobile" border="none" placeholder="手机号"></up-input>
                </up-form-item>
                <up-form-item label="选择地区"  borderBottom>
                    <view class="flex justify-between items-center">
                        <up-input :disabled="true" v-model="form.name" border="none" placeholder="省、市、区"></up-input>
                        <view class="flex items-center" @click="checkAddress">
                            <image src="../static/haddress.png" mode="scaleToFill" class="w-[36rpx] h-[36rpx] block"/>
                            <view class="text-[28rpx] text-[#666] ml-[4rpx] font-normal">定位</view>
                        </view>
                    </view>
                </up-form-item>
                <up-form-item label="详细地址" prop="address" :borderBottom="false">
                    <up-textarea v-model="form.address" border="none" maxlength="100" :count="true" placeholder="如校区、楼栋号、门牌号等" ></up-textarea>
                    <!-- <up-input v-model="form.address" border="none" placeholder="如校区、楼栋号、门牌号等"></up-input> -->
                </up-form-item>
            </up-form>
        </view>
        <view class="bg-[#fff] flex justify-between items-center p-[30rpx]" @click="form.isDefault=!form.isDefault">
            <view class="text-[28rpx] text-[#101010] font-normal">设为默认地址</view>
                <view>
                    <image v-if="form.isDefault" src="../static/gou-fill.png" mode="scaleToFill" class="w-[28rpx] h-[28rpx] block"/>
                    <image v-else src="../static/kuang.png" mode="scaleToFill" class="w-[28rpx] h-[28rpx] block"/>
                </view>
            </view>
        <view @click="submit" class="tr bottom-[120rpx] left-[50%] text-center absolute w-[622rpx] py-[26rpx] rounded-[40rpx] bg-[#46A7FD] text-[32rpx] text-[#fff] font-normal">提交</view>
    </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue';
import { AddAddress, AddressDetail, UpdataAddress } from '../../API/user';
import { showToast } from '../../utils/utils';
let form = ref({
    receiveName:'',
    mobile:'',
    province:'湖北省',
    city:'武汉市',
    area:'武昌区',
    address:'',
    isDefault:true
})
const uFormRef = ref(null); 
const errorType = ref('message');
function changeErrorType() {  
  errorType.value = 'border-bottom'; // 假设你想要切换到下划线提示  
}  
const rules = ref({
    receiveName:[{
        required:true,
        message:'请输入收货人',
        trigger:['blur','change']
    }],
    mobile: [{
		required: true, 
		message: '请输入手机号',
		trigger: ['change','blur'],
	},{
		validator: (rule, value, callback) => {
			return uni.$u.test.mobile(value);
		},
		message: '手机号码不正确',
		trigger: ['change','blur'],
	}],
    address:[{
        required:true,
        message:'请输入详细地址',
        trigger:['blur','change']
    }]
})
const checkAddress = ()=>{
    uni.chooseLocation({
        success:(res)=>{
            let {province,city,district,detail} = splitAddress(res.address)
            form.value.province = province
            form.value.city = city
            form.value.area = district
            form.value.address = detail
            form.value.name = `${province}-${city}-${district}`
            console.log(res);
        },
        error:(err)=>{
            console.log(err);
        }
    })
}
function splitAddress(address) {
    // 这是一个非常简化的正则表达式，用于匹配省、市、区（县）和详细地址
    // 在实际应用中，你可能需要根据具体的地址格式进行调整
    const regex = /^([^省]+省)?([^市]+市)?([^区]+区|[^县]+县)?(.*)$/;
    const matches = address.match(regex);
 
    if (matches) {
        return {
            province: matches[1] || '', // 省
            city: matches[2] || '',     // 市
            district: matches[3] || '', // 区/县
            detail: matches[4].trim()   // 详细地址
        };
    } else {
        return {
            province: '',
            city: '',
            district: '',
            detail: address.trim() // 如果无法匹配，则整个地址作为详细地址返回
        };
    }
}
 
function submit (){
    uFormRef.value.validate().then(valid => {  
        if (valid) {
            if(form.value.id){
                addressUpdate()
            }else{
                addressTian()
            }
        }
    }).catch(() => {  
        uni.$u.toast('校验失败')
    });
}
async function addressTian(){
    let res = await AddAddress(form.value)
    showToast('添加地址成功')
    uni.navigateBack()
}
async function addressUpdate(){
    let res = await UpdataAddress(form.value)
    showToast('修改地址成功')
    uni.navigateBack()
}
async function addressDelt(id) {
    let { data } = await AddressDetail(id)
    form.value = data
}
function goback(){
    uni.navigateBack()
}
function gohome(){
    uni.switchTab({
        url:'/pages/index/index'
    })
}
onLoad(async (options)=>{
    if(options.id){
        await addressDelt(options.id)
    }
})
</script>

<style lang="scss" scoped>
.tr{
    transform: translate(-50%,0);
}
</style>